//
//  HomeViewController.m
//  eGifr
//
//  Created by Phien Tram on 8/4/13.
//  Copyright (c) 2013 eGiftr. All rights reserved.
//

#import "HomeViewController.h"
#import "RegisterViewController.h"
#import <FacebookSDK/FacebookSDK.h>
#import "UserDefaultHelper.h"
#import "AppDelegate.h"
#import "NSDictionary+Utility.h"
#import "ServiceNameMapper.h"
#import "Global.h"
#import "FindKeyword.h"

@interface HomeViewController () <RegisterViewDelegate>

/*
 "fbId":"String content",
 "fbToken":"String content",
 "isFbUser":true,
 "login":"String content",
 */
@property (nonatomic, strong) NSString *fbId;
@property (nonatomic, strong) NSString *fbToken;
@property (nonatomic, strong) NSString *fbUsername;
@property (nonatomic, assign) BOOL isFbUser;
@property (nonatomic, strong) NSString *fbEmail;
@end

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    CGSize contentSize = self.scrollView.contentSize;
    contentSize.height = 504;
    self.scrollView.contentSize = contentSize;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [super viewWillDisappear:animated];
}

- (void)viewDidUnload {
    [self setUsernameTextField:nil];
    [self setPasswordTextField:nil];
    [super viewDidUnload];
}

#pragma mark - Navigation

// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([segue.identifier isEqualToString:@"RegisterPush"])
	{
        RegisterViewController *viewController = segue.destinationViewController;
        viewController.delegate = self;
	}
}

#pragma mark - IBAction methods

- (IBAction)forgotPasswordButtonOnClicked:(id)sender
{
    
}

- (IBAction)loginButtonOnClicked:(id)sender
{
    NSString *message = @"";
    if (_usernameTextField.text.length == 0 || _passwordTextField.text.length == 0) {
        message = @"Username or password is invalid! Please try again.";
    }
    if (message.length > 0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sorry" message:message delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
        [alertView show];
    } else {
        [SharedAppDelegate startSpinner:@"Loading..."];
        self.dataManager = [DataManager login:self isFbUser:[NSNumber numberWithBool:NO] login:_usernameTextField.text password:_passwordTextField.text];
    }
//    if ([_usernameTextField.text isEqualToString:[UserDefaultHelper getEmailAddress]]
//        && [_passwordTextField.text isEqualToString:[UserDefaultHelper getPassword]])
//    {
//        [self.navigationController popToRootViewControllerAnimated:NO];
//        [_delegate homeViewLoginSuccessful:self];
//    }
}

- (IBAction)loginFacebookButtonOnClicked:(id)sender
{
    [SharedAppDelegate startSpinner:@"Loading..."];
    // if the session is open, then load the data for our view controller
    if (FBSession.activeSession.isOpen) {
        [self getFacebookUserProfileInfo:YES];
    } else {
        // if the session isn't open, we open it here, which may cause UX to log in the user
        NSArray *permissions = [[NSArray alloc] initWithObjects:
                                @"email",
                                @"user_location",
                                @"user_birthday",
                                @"user_likes",
                                @"user_interests",
                                @"user_relationships",
                                @"friends_location",
                                @"friends_birthday",
                                @"friends_likes",
                                @"friends_interests",
                                @"friends_relationships",
                                @"read_stream",
                                @"read_friendlists",
                                nil];
        [FBSession openActiveSessionWithReadPermissions:permissions
                                           allowLoginUI:YES
                                      completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
                                          if (error) {
                                              [[[UIAlertView alloc] initWithTitle:@"Error"
                                                                          message:error.localizedDescription
                                                                         delegate:nil
                                                                cancelButtonTitle:@"OK"
                                                                otherButtonTitles:nil]
                                               show];
                                          } else {
                                              //get email, id and then validate facebook account
                                              [self getFacebookUserProfileInfo:YES];
                                          }
                                      }];
    }
}

#pragma mark - RegisterViewController delegate

- (void)registerViewSuccessful:(RegisterViewController *)viewController
{
    [self.navigationController popToRootViewControllerAnimated:NO];
    
    [_delegate homeViewLoginSuccessful:self];
}

#pragma mark - Private methods

- (void)getFacebookUserProfileInfo:(BOOL)isNewUser
{
    // Fetch user data
    [FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id<FBGraphUser> user, NSError *error) {
        
        if (!error) {
            NSLog(@"userInfo: %@", [user description]);
            self.isFbUser = YES;
            self.fbId = [user id];
            self.fbToken = [FBSession activeSession].accessTokenData.accessToken;
            self.fbUsername = [user username];
            self.fbEmail = [user objectForKey:@"email"];
            NSString *urlString = [NSString stringWithFormat:@"http://graph.facebook.com/%@/picture?type=large", user.id];
            [UserDefaultHelper setImageProfileUrl:urlString];
            
            id<FBGraphLocation> location = (id)[user location];
            NSString *locationName = [location objectForKey:@"name"];
            //Geocoding here
            CLGeocoder *gc = [[CLGeocoder alloc] init];
            [gc geocodeAddressString:locationName completionHandler:^(NSArray *placemarks, NSError *error)
             {
                 if ([placemarks count]>0)
                 {
                     // get the first one
                     CLPlacemark *mark = (CLPlacemark *)[placemarks objectAtIndex:0];
                     double lat = mark.location.coordinate.latitude;
                     double lng = mark.location.coordinate.longitude;
                     NSLog(@"lat:%f lng:%f", lat, lng);
                     [UserDefaultHelper setCity:[mark locality]];
                     [UserDefaultHelper setLatitude:lat];
                     [UserDefaultHelper setLongitude:lng];
                 }
                 
//                 [_delegate homeViewLoginSuccessful:self];
             }];
            
            if (isNewUser) {
                self.dataManager = [DataManager userRegister:self userName:_fbUsername email:@"" password:@"" city:@"" fbId:_fbId fbToken:_fbToken isFbUser:_isFbUser];
            } else {
                self.dataManager = [DataManager login:self isFbUser:[NSNumber numberWithBool:YES] login:_fbUsername password:@""];
            }
            
        } else {
            [SharedAppDelegate stopSpinner];
        }
    }];
//    FBAccessTokenData *tokenData = [FBSession activeSession].accessTokenData;
//    NSLog(@"TokenData: %@", [tokenData dictionary]);
}

- (void)onSuccessfulLogin
{
    [SharedAppDelegate startSpinner:@"Loading..."];
    self.dataManager = [DataManager findKeywords:self query:@"" cate:@"" appToken:[UserDefaultHelper getAppToken]];
}

- (FindKeyword *)findKeywordObject:(NSString *)text
{
    NSArray *allKeywords = [Global sharedGlobal].allKeywords;
    FindKeyword *result = nil;
    for (FindKeyword *keyword in allKeywords) {
        if ([keyword.keyword isEqualToString:text]) {
            result = keyword;
            break;
        }
    }
    
    return result;
}


#pragma mark - UITextField delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - DataManager delegate

- (void)dataManagerFinishGetData:(DataManager *)dataManager response:(id)response error:(NSError *)error
{
    [SharedAppDelegate stopSpinner];
    
    if (error) {
        if ([dataManager.serviceName isEqualToString:[ServiceNameMapper login]]) {
            
        } else if ([dataManager.serviceName isEqualToString:[ServiceNameMapper userRegister]]) {
            if ([error code] == 200) {
                /*
                 error =     {
                 details = "This user is already in our file";
                 errorCode = 200;
                 errorMessage = "The paramater is invalid.";
                 };
                 */
                //fb account has already been registered.
                //We should call login with facebook account
                if (self.fbUsername && self.fbToken) {
                    //already got profile
                    [SharedAppDelegate startSpinner:@"Loading..."];
                    self.dataManager = [DataManager login:self isFbUser:[NSNumber numberWithBool:YES] login:_fbUsername password:@""];
                } else {
                    if (FBSession.activeSession.isOpen) {
                        [self getFacebookUserProfileInfo:NO];
                    } else {
                        // if the session isn't open, we open it here, which may cause UX to log in the user
                        NSArray *permissions = [[NSArray alloc] initWithObjects:
                                                @"email",
                                                @"user_location",
                                                @"user_birthday",
                                                @"user_likes",
                                                @"user_interests",
                                                @"user_relationships",
                                                @"friends_location",
                                                @"friends_birthday",
                                                @"friends_likes",
                                                @"friends_interests",
                                                @"friends_relationships",
                                                @"read_stream",
                                                @"read_friendlists",
                                                nil];
                        [FBSession openActiveSessionWithReadPermissions:permissions
                                                           allowLoginUI:YES
                                                      completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
                                                          if (error) {
                                                              [[[UIAlertView alloc] initWithTitle:@"Error"
                                                                                          message:error.localizedDescription
                                                                                         delegate:nil
                                                                                cancelButtonTitle:@"OK"
                                                                                otherButtonTitles:nil]
                                                               show];
                                                          } else {
                                                              //get email, id and then validate facebook account
                                                              [self getFacebookUserProfileInfo:NO];
                                                          }
                                                      }];
                    }
                }
            }
        }
//        else if ([dataManager.serviceName isEqualToString:[ServiceNameMapper saveWishesByUserId]]) {
//            if ([error code] == 600) {
//                [_delegate homeViewLoginSuccessful:self];
//            }
//        }
        else {
            NSLog(@"ERROR: %@", error.localizedDescription);
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sorry" message:error.localizedDescription delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
            [alertView show];
        }
    } else {
        NSLog(@"Response: %@", response);
        if ([dataManager.serviceName isEqualToString:[ServiceNameMapper login]]) {
            /*
             data =     {
             appToken = 5B373fkv2Kw96ap6RZ4zX71wOkx71YpfLTf26IGR4m1g6Oty75W2q4k40y969U4Oove4F9406677d4355Al0mZ6V5k58C400F05M;
             fbId = "<null>"; //100000920651234
             login = phientest2;
             userId = "2e5d6bc6-8ea2-4dca-b5de-08d0779d0f8b";
             };
             */
            if (response) {
                NSDictionary *data = (NSDictionary *)response;
                NSString *userId = [data objectOrNilForKey:@"userId"];
                [UserDefaultHelper setUserId:userId];
                [UserDefaultHelper setAppToken:[data objectOrNilForKey:@"appToken"]];
            }
            
            if (_fbId) {
                [UserDefaultHelper setFbId:_fbId];
                [UserDefaultHelper setUsername:_fbUsername];
                [UserDefaultHelper setEmailAddress:_fbEmail];
                
            } else {
                [UserDefaultHelper setUsername:_usernameTextField.text];
                [UserDefaultHelper setPassword:_passwordTextField.text];
            }
            
            if ([UserDefaultHelper getAppToken].length > 0) {
                [self onSuccessfulLogin];
            } else {
                [_delegate homeViewLoginSuccessful:self];
            }
        } else if ([dataManager.serviceName isEqualToString:[ServiceNameMapper userRegister]]) {
            if (response) {
                NSDictionary *data = (NSDictionary *)response;
                NSString *userId = [data objectOrNilForKey:@"userId"];
                [UserDefaultHelper setUserId:userId];
                [UserDefaultHelper setAppToken:[data objectOrNilForKey:@"appToken"]];
            }
            
            [UserDefaultHelper setEmailAddress:_fbEmail];
            [UserDefaultHelper setUsername:_fbUsername];
            [UserDefaultHelper setFbId:_fbId];
            
            [SharedAppDelegate startSpinner:@"Loading..."];
            self.dataManager = [DataManager login:self isFbUser:[NSNumber numberWithBool:YES] login:_fbUsername password:@""];
//            if ([UserDefaultHelper getAppToken].length > 0) {
//                [self onSuccessfulLogin];
//            } else {
//                [_delegate homeViewLoginSuccessful:self];
//            }
        } else if ([dataManager.serviceName isEqualToString:[ServiceNameMapper findKeywords]]) {
            [Global sharedGlobal].allKeywords = response;
            
            //waiting for saving wishlist before close home screen
            [SharedAppDelegate startSpinner:@"Loading..."];
            NSArray *wishList = [UserDefaultHelper getMyWishList];
            NSMutableArray *mutableArray = [NSMutableArray array];
            for (NSString *text in wishList) {
                FindKeyword *found = [self findKeywordObject:text];
                if (found) {
                    [mutableArray addObject:found];
                }
            }
            self.dataManager = [DataManager saveWishesByUserId:self userId:[UserDefaultHelper getUserId] keywords:[NSArray arrayWithArray:mutableArray] appToken:[UserDefaultHelper getAppToken]];
        } else if ([dataManager.serviceName isEqualToString:[ServiceNameMapper saveWishesByUserId]]) {
            [_delegate homeViewLoginSuccessful:self];
        } else {
            
        }
        
    }
}

@end
